const _exec = require('child_process').exec;
const fs = require('fs');
const path = require('path');

function exec(cmd) {
    return new Promise((res) => {
        _exec(cmd, (e, out) => {
                if (e) console.warn("error:", e);
                else res(out);
            }
        )
    })
}

async function transform({src, dest, json}){
    await exec(`unzip -oq ${src} -d tmp1`);
	
	let args=[], argNs=[];
	for (var prop in json){
		args.push(json[prop]);
		argNs.push(prop);
	}

					
	let re=/\$\{([^\}]*)\}/;
	
	function traverse(dir){
		for (let filename of fs.readdirSync(dir)){
			let filedir = path.join(dir,filename);
			console.log(`traversing: ${filedir}`);
			let stats=fs.statSync(filedir);
			var isFile = stats.isFile();     //是文件
			var isDir = stats.isDirectory(); //是文件夹
			if (isFile && filedir.indexOf(".xml")>=0){
				let str=fs.readFileSync(filedir,{encoding:"utf8"});
				while (re.test(str)) {
					let cmd=`return ${RegExp.$1}`;
                    str=str.replace(re, new Function(...argNs,cmd)(...args));
                }
                fs.writeFileSync(filedir,str);
			}
			if(isDir)
				traverse(filedir);
			console.log(`${filedir} ok`);
		}
	}
	try {
		traverse("tmp1");
	}catch(e){
		console.warn("error,",e);
	}
	console.log("zip start");
	console.log("__dirname",__dirname);
    await exec(`toExcel.bat ${dest}`);
	console.log("transform complete");
}
// transform({src:"test.xlsx",dest:"out",json:{a:"hello", e:"a"}});
module.exports=transform;